export default class CountdownTimer {
    private remain: number = 0;        // 结束时间（秒级）
    private intervalId: number = null;  // 定时器ID
    private callback: (remain: number, status: string) => void;

    /**
     * 创建倒计时实例
     * @param remain 倒计时时间（秒）
     * @param callback 每秒回调函数（剩余秒数，状态，格式化时间）
     */
    constructor(
        remain: number,
        callback: (remain: number, status: string) => void,
    ) {
        this.remain = remain;
        this.callback = callback;
        this.startTicking();
    }

    // 启动定时器
    private startTicking() {
        this.intervalId = setInterval(() => this.tick(), 1000) as unknown as number;
        this.tick(); // 立即执行第一次
    }

    // 核心计时逻辑
    private tick() {
        let status = '';
         if (this.remain != 0) {
            status = 'running';
    
        } else {
            status = 'ended';
            this.stop();
        }

        if (this.callback) {
            this.callback(
                this.remain,
                status,
            );
        }
        if (this.remain != undefined && this.remain != null && status == 'running') {
            this.remain--; 
        }
    }

    // 更新服务器时间（外部同步用）
    updateServerTime(remain: number) {
        this.remain = remain;
    }

    // 停止计时器
    stop() {
        clearInterval(this.intervalId);
        this.intervalId = null;
        this.callback = null;
    }

    // 销毁实例
    destroy() {
        this.stop();
        this.callback = null;
    }
}